package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.College;
import pojo.Question;
import service.BackCollegeService;
import service.BackForumService;
import serviceImpl.BackCollegeServiceImpl;
import serviceImpl.BackForumServiceImpl;


@WebServlet("/BackForumServlet")
public class BackForumServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public BackForumServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String mark = request.getParameter("mark");
		switch(mark) {
		case "showQuestion": 
			showQuestion(request,response);
			break;
		case "addQuestion": 
			addQuestion(request,response);
			break;
		case "delQuestion": 
			delQuestion(request,response);
			break;
		
		}
	}


	private void delQuestion(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		int qid = Integer.parseInt(request.getParameter("qid"));
		System.out.println("qid:"+qid);
		BackForumService bfs = new BackForumServiceImpl();
		boolean bo = bfs.delQuestion(qid);
		System.out.println(bo);
		
		PrintWriter writer = response.getWriter();
		writer.print(bo);
		
	}


	private void addQuestion(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String qTitle = request.getParameter("qTitle");
		String qContent = request.getParameter("qContent");
		int userid = Integer.parseInt(request.getParameter("userid"));
		
		BackForumService bfs = new BackForumServiceImpl();
		boolean suc = bfs.addQuestion(qTitle,qContent,userid);
		System.out.println("suc:"+suc);
		PrintWriter writer = response.getWriter();
		writer.print(suc);
		
	}


	private void showQuestion(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		BackForumService bfs = new BackForumServiceImpl();
		ArrayList<Question> qList = new ArrayList<Question>();
		qList = bfs.getQuestion();
		request.setAttribute("questionList", qList);
		request.getRequestDispatcher("/background/ordUserJs/index/question.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
